<script setup lang="ts" name="DrugStorehouse">
import {ColorTheme, ColorRed} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import {defaultLayout, defaultPage, defaultPageSize, defaultPageSizes, PageConfig} from '@/components/dTable/dFooter'
import {OperButton, SearchFromItem, SearchButton} from '@/components/dTable/dHeader'
import {HeaderData, RowOperbuttons, Operation as Oper} from '@/components/dTable/dTable'
import operation from '@/components/dTable/components/operation.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import AddDrugStorehouse from './addDrugStorehouse.vue'
import {ElMessage, FormRules} from 'element-plus'
import {onBeforeMount, reactive, ref} from 'vue'
import {deleteDrugStore, DrugStoreList, getDrugStore} from '@/api/medicalExaminerDesk/beginPhysicalExamination/mainMedication'
import {showMessageBox} from '@/util/element'
import {NoChinese, NotLeadingAndTrailingSpaces} from '@/util/common'
defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  }
})

// 新增或者编辑弹窗
const showAddDrugDialog = ref(false)

// 新增或者编辑弹窗类型
const dialogType = ref('')

// 空数据
const emptyData: DrugStoreList = {
  drugCode: '', // 药品代码
  drugName: '', // 药品名称
  pinyinCode: '', // 拼音码
  dose: '' // 用药剂量
}

// 药品库数据
const drugData = ref<DrugStoreList>({...emptyData})

const emits = defineEmits(['close'])

//显示加载状态
const showLoading = ref(false)

//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])

//搜索项
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '药品代码',
    placeholder: '请输入药品代码',
    type: 'input',
    prop: 'drugCode',
    enterSubmit: true
  },
  {
    label: '药品名称',
    placeholder: '请输入药品名称',
    type: 'input',
    prop: 'drugName',
    enterSubmit: true
  }
])
// 表格搜索
const searchFromData = reactive({})
// 表格搜索校验
const searchFromRules = reactive<FormRules>({
  drugCode: [
    {
      message: '最多50位字母、数字、字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母、数字、字符',
      pattern: NoChinese,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  drugName: [
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'drugCode',
    label: '药品代码',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'drugName',
    label: '药品名称',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'drugUseMethodName',
    label: '用法',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'doseName',
    label: '用量',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'drugUseTimeName',
    label: '用药时间',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'drugCompliableName',
    label: '服药依从性',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '80',
    fixed: 'right'
  }
])

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

//数据
const tableData = ref<Array<DrugStoreList & RowOperbuttons>>([])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

// 行操作按钮
const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {
      icon: 'common-edit',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  },
  {
    code: 'delete',
    label: '删除',
    iconConfig: {
      icon: 'common-delete',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

//后端数据拼接字段
const setTableData = (data: Array<DrugStoreList>) => {
  const dataArr: Array<DrugStoreList & RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, oper: rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  getDrugStore({
    ...searchFromData,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      const {records} = res.data.data
      pageConfig.value.total = res.data.data.total === null ? 0 : res.data.data.total
      setTableData(records)
    })
    .catch((error) => {
      console.warn(error)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//操作按钮事件
const onOperation = (code: string) => {
  if (code === 'add') {
    drugData.value = {...emptyData} // 清空数据
    dialogType.value = 'add'
    showAddDrugDialog.value = true
  }
}

//操作插槽事件
const cellOperation = (code: string, row: DrugStoreList) => {
  if (code === 'edit') {
    drugData.value = {
      id: row.id,
      drugName: row.drugName, // 药品名称
      drugCode: row.drugCode, // 药品代码
      pinyinCode: row.pinyinCode, // 拼音码
      drugUseMethod: row.drugUseMethod, // 用法 - 字典
      frequency: row.frequency, // 用药频率 - 字典
      dose: row.dose, // 用药剂量
      doseUnit: row.doseUnit, // 用药剂量单位 - 字典
      drugTimeUnit: row.drugTimeUnit, //用药时间单位 - 字典
      drugUseTime: row.drugUseTime ? Number(row.drugUseTime) : undefined, // 用药时间
      drugCompliable: row.drugCompliable // 服药依从性 - 字典
    }
    dialogType.value = 'edit'
    showAddDrugDialog.value = true
  } else if (code === 'delete') {
    showMessageBox('是否确认删除此药品？', {title: '删除确认', mesageType: 'base'})
      .then(() => {
        row.id &&
          deleteDrugStore(row.id).then(() => {
            ElMessage.success('删除成功！')
            searchData()
          })
      })
      .catch((error) => {
        console.warn(error)
      })
  }
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

/**
 * @description: 关闭新增保存弹窗
 * @return {*}
 */
const onCloseDrugDialog = () => {
  showAddDrugDialog.value = false
  searchData()
}

/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onCancel = () => {
  emits('close')
}
/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onClose = () => {
  emits('close')
}

onBeforeMount(() => {
  searchData()
})
</script>
<template>
  <d-dialog
    title="药品库维护"
    :show-dialog="showDialog"
    :hide-save-btn="true"
    cancel-text="关闭"
    :width="1100"
    @cancel="onCancel"
    @close="onClose"
  >
    <d-table-promote
      :oper-buttons="operButtons"
      :search-form-items="searchFromItems"
      :search-buttons="searchButtons"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      search-from-justify="flexStart"
      class="drug-storehouse-table"
      :show-loading="showLoading"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
    </d-table-promote>
  </d-dialog>
  <add-drug-storehouse v-if="showAddDrugDialog" :drug-data="drugData" :show-dialog="showAddDrugDialog" :dialog-type="dialogType" @close="onCloseDrugDialog" />
</template>
<style scoped lang="less">
.drug-storehouse-table {
  height: 600px;
}
</style>
